#!/bin/bash

# Ubuntu桌面环境 - 网络冲突解决脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}  网络冲突解决脚本${NC}"
    echo -e "${BLUE}================================${NC}"
}

# 检查Docker服务
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker未安装"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        print_error "Docker服务未运行"
        exit 1
    fi
}

# 显示当前网络状态
show_networks() {
    print_message "当前Docker网络状态："
    echo
    docker network ls --format "table {{.Name}}\t{{.Driver}}\t{{.Scope}}\t{{.IPv4}}"
    
    echo
    print_message "网络详细信息："
    for network in $(docker network ls --format "{{.Name}}" | grep -E "(desktop|ubuntu)"); do
        echo "网络: $network"
        docker network inspect $network --format "  Subnet: {{range .IPAM.Config}}{{.Subnet}}{{end}}"
        echo
    done
}

# 清理冲突的网络
cleanup_conflicting_networks() {
    print_message "清理冲突的网络..."
    
    # 停止所有相关容器
    print_message "停止相关容器..."
    docker-compose -f docker-compose.lightweight.yml down 2>/dev/null || true
    docker-compose down 2>/dev/null || true
    
    # 删除冲突的网络
    print_message "删除冲突的网络..."
    docker network rm ubuntu-desktop_desktop-network 2>/dev/null || true
    docker network rm ubuntu-desktop_desktop-network-lightweight 2>/dev/null || true
    docker network rm ubuntu-desktop_desktop-network-standard 2>/dev/null || true
    
    # 清理未使用的网络
    print_message "清理未使用的网络..."
    docker network prune -f
    
    print_message "网络清理完成"
}

# 检查端口占用
check_port_conflicts() {
    print_message "检查端口占用情况..."
    
    local ports=("5900" "5901" "2222" "2223")
    
    for port in "${ports[@]}"; do
        if netstat -tlnp 2>/dev/null | grep -q ":$port "; then
            print_warning "端口 $port 被占用"
            netstat -tlnp 2>/dev/null | grep ":$port "
        else
            print_message "端口 $port 可用"
        fi
    done
}

# 重新创建网络
recreate_networks() {
    print_message "重新创建网络..."
    
    # 创建轻量级网络
    print_message "创建轻量级网络..."
    docker network create --driver bridge --subnet 172.25.0.0/16 ubuntu-desktop_desktop-network-lightweight 2>/dev/null || true
    
    # 创建标准网络
    print_message "创建标准网络..."
    docker network create --driver bridge --subnet 172.26.0.0/16 ubuntu-desktop_desktop-network-standard 2>/dev/null || true
    
    print_message "网络创建完成"
}

# 测试网络连接
test_networks() {
    print_message "测试网络连接..."
    
    # 测试轻量级网络
    if docker network ls | grep -q "ubuntu-desktop_desktop-network-lightweight"; then
        print_message "轻量级网络创建成功"
    else
        print_error "轻量级网络创建失败"
    fi
    
    # 测试标准网络
    if docker network ls | grep -q "ubuntu-desktop_desktop-network-standard"; then
        print_message "标准网络创建成功"
    else
        print_error "标准网络创建失败"
    fi
}

# 显示解决方案
show_solutions() {
    echo
    echo -e "${GREEN}================================${NC}"
    echo -e "${GREEN}  网络冲突解决方案${NC}"
    echo -e "${GREEN}================================${NC}"
    echo
    
    echo "已执行的解决方案："
    echo "1. ✅ 清理了冲突的网络"
    echo "2. ✅ 重新创建了网络（使用不同子网）"
    echo "3. ✅ 检查了端口占用情况"
    echo
    
    echo "网络配置更新："
    echo "  - 轻量级版本: 172.25.0.0/16"
    echo "  - 标准版本: 172.26.0.0/16"
    echo
    
    echo "现在可以重新启动服务："
    echo "  - 轻量级版本: docker-compose -f docker-compose.lightweight.yml up -d"
    echo "  - 标准版本: docker-compose up -d"
    echo "  - 或使用脚本: ./start-linux.sh"
    echo
}

# 主函数
main() {
    print_header
    
    # 检查Docker
    check_docker
    
    # 显示当前网络状态
    show_networks
    
    echo
    read -p "是否继续清理冲突的网络？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_message "用户取消操作"
        exit 0
    fi
    
    # 清理冲突的网络
    cleanup_conflicting_networks
    
    # 检查端口占用
    check_port_conflicts
    
    # 重新创建网络
    recreate_networks
    
    # 测试网络
    test_networks
    
    # 显示解决方案
    show_solutions
}

# 捕获信号
trap 'print_error "脚本被中断"; exit 1' INT TERM

# 运行主函数
main "$@" 